package com.xbongbong.paas.help.team;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Streams;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.BusinessUserTeamHelp;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.FormTeamSetEntity;
import com.xbongbong.pro.enums.FieldAdvanceOperationEnum;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.UserTeamErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.HandoverPermissionAliasEnum;
import com.xbongbong.pro.enums.teammembers.enums.CoUserPermissionEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormCoUserDefaultPermissionEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormDefaultPatternEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormOwnerUniqueEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormPatternEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.listbatch.pojo.TeamBatchPojo;
import com.xbongbong.pro.permission.pojo.dto.VerifyUpdatePermissionDTO;
import com.xbongbong.pro.team.TeamAfterModeProcessPOJO;
import com.xbongbong.pro.team.TeamAfterVerifyDTO;
import com.xbongbong.pro.team.TeamFieldExplainPOJO;
import com.xbongbong.pro.team.TeamModelProcessMidPOJO;
import com.xbongbong.pro.team.TeamUserListPOJO;
import com.xbongbong.pro.team.TeamVerifyDTO;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.teammembers.TeamMembersConstant;
import com.xbongbong.saas.domain.entity.ClueRuleEntity;
import com.xbongbong.saas.domain.entity.CustomerRuleEntity;
import com.xbongbong.saas.domain.entity.ShareRuleEntity;
import com.xbongbong.saas.domain.entity.TransferBackRuleSeniorEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.ClueRuleEnum;
import com.xbongbong.saas.enums.ClueSeniorRuleTypeEnum;
import com.xbongbong.saas.enums.CustomerRuleEnum;
import com.xbongbong.saas.enums.CustomerSeniorRuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.UserTeamOperateTagEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.factory.publicrule.CheckRuleMaxClueNum;
import com.xbongbong.saas.factory.publicrule.CheckRuleMaxCustomerNum;
import com.xbongbong.saas.model.ClueRuleModel;
import com.xbongbong.saas.model.CustomerRuleModel;
import com.xbongbong.saas.model.TransferBackRuleSeniorModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.DataPermissionEnum;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 * @author 魏荣杰
 *
 */
@Component
@Slf4j
public class TeamUserHelp {

    @Resource
    private UserModel userModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private BusinessUserTeamHelp businessUserTeamHelp;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private FormTeamSetHelp formTeamSetHelp;
    @Resource
    private CheckRuleMaxCustomerNum checkRuleMaxCustomerNum;
    @Resource
    private CheckRuleMaxClueNum checkRuleMaxClueNum;
    @Resource
    private CustomerRuleModel customerRuleModel;
    @Resource
    private ClueRuleModel clueRuleModel;
    @Resource
    private TransferBackRuleSeniorModel transferBackRuleSeniorModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private FormDataHelp formDataHelp;
    @Resource
    private ProPermissionHelp proPermissionHelp;




    /**
     * paas表单有点特殊的地方，新增的场景：负责人字段不存在用创建人作为负责人；负责人字段存在但是负责人字段没填也用当前创建人作为负责人
     *        编辑的场景：负责人字段存在的话，填啥是啥；负责人字段不存在的话，还是用创建人作为负责人
     *
     * @param validateDataDTO
     * @throws XbbException
     */
    public void beforeVerifyUserTeam(ValidateDataDTO validateDataDTO) throws XbbException {
//        TeamStrategy teamStrategy = teamStrategyMap.get(validateDataDTO.getBusinessType());
        Integer saasMark = validateDataDTO.getSaasMark();
        TeamVerifyDTO teamVerifyDTO = new TeamVerifyDTO();
        BeanUtil.copyProperties(validateDataDTO, teamVerifyDTO);
        boolean isNew = Objects.isNull(validateDataDTO.getDataId()) || Objects.equals(validateDataDTO.getDataId(), 0L);
        String creatorId = StringUtil.isNotEmpty(validateDataDTO.getCreatorId()) ? validateDataDTO.getCreatorId() : validateDataDTO.getUserId();
        teamVerifyDTO.setFromDetail(false);
        teamVerifyDTO.setIsNew(isNew);
        teamVerifyDTO.setDataId(Collections.singletonList(validateDataDTO.getDataId()));
        teamVerifyDTO.setCreatorId(creatorId);
        if (Objects.nonNull(validateDataDTO.getFromApproval())) {
            //兼容一下联合审批的场景下，如果上游业务都不需要校验团队权限，那么下游业务也不应该校验团队权限
            teamVerifyDTO.setFromApproval(validateDataDTO.getFromApproval());
        }else {
            teamVerifyDTO.setFromApproval(Objects.nonNull(validateDataDTO.getTaskId()));
        }
        teamVerifyDTO.setFromCover(Objects.equals(validateDataDTO.getIsCover(), BasicConstant.ONE));
        List<ReturnUserAndDepartmentPojo> ownerList = validateDataDTO.getOwnerIds();
        List<ReturnUserAndDepartmentPojo> coUserList = validateDataDTO.getCoUserId();
        Set<String> ownerIdList = new HashSet<>();
        Set<String> coUserIdList = new HashSet<>();
        if (CollectionsUtil.isNotEmpty(ownerList)) {
            ownerList.forEach(owner -> ownerIdList.add(Objects.toString(owner.getId(), "")));
        }
        if (CollectionsUtil.isNotEmpty(coUserList)) {
            coUserList.forEach(coUser -> coUserIdList.add(Objects.toString(coUser.getId(), "")));
        }
        //paas表单有个特殊业务场景就是，如果ownerIdList为空，就用创建人id作为负责人id
        if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark) && CollectionsUtil.isEmpty(ownerIdList)) {
            TeamFieldExplainPOJO teamFieldExplainPOJO = getTeamFieldExplain(validateDataDTO.getCorpid(), validateDataDTO.getFormId(), validateDataDTO.getBusinessType());
            FieldAttrEntity ownerField = teamFieldExplainPOJO.getOwnerField();
            if (Objects.isNull(ownerField) || isNew) {
                //这里的判断主要是为了解决工作流那边的，一定要有负责人字段的值，不然会把负责人删除掉。
                ownerIdList.add(creatorId);
            }
        }
        teamVerifyDTO.setNewAddMainUserList(ownerIdList);
        teamVerifyDTO.setNewAddCoUserList(coUserIdList);
//        TeamAfterVerifyDTO teamAfterVerifyDTO = teamStrategy.verify(teamVerifyDTO);
        TeamAfterVerifyDTO teamAfterVerifyDTO = verifyFromForm(teamVerifyDTO);
        SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo = validateDataDTO.getSaasNeedRedundantAttrPoJo() == null ?
                new SaasNeedRedundantAttrPojo() : validateDataDTO.getSaasNeedRedundantAttrPoJo();
        saasNeedRedundantAttrPojo.setTeamAfterVerifyDTO(teamAfterVerifyDTO);
        validateDataDTO.setSaasNeedRedundantAttrPoJo(saasNeedRedundantAttrPojo);

        List<TeamBatchPojo> teamBatchPojos = teamAfterVerifyDTO.getTeamBatchPojos();
        if (CollectionsUtil.isNotEmpty(teamBatchPojos)) {
            throw new XbbException(teamBatchPojos.get(0).getCode(), teamBatchPojos.get(0).getFailMsgReason());
        }
    }

    /**
     * Description: 校验团队（新建/编辑）
     * @param teamVerifyDTO
     * @return com.xbongbong.pro.team.TeamAfterVerifyDTO
     * @throws
     * @author 魏荣杰
     * @date 2022/1/5 20:17
     * @since
     */
    public TeamAfterVerifyDTO verifyFromForm(TeamVerifyDTO teamVerifyDTO) throws XbbException {
        String corpid = teamVerifyDTO.getCorpid();
        List<Long> dataIdIn = teamVerifyDTO.getDataId();
        Long formId = teamVerifyDTO.getFormId();
        Integer saasMark = teamVerifyDTO.getSaasMark();
        Integer businessType = teamVerifyDTO.getBusinessType();
        Integer distributorMark = teamVerifyDTO.getDistributorMark();
        Integer subBusinessType = teamVerifyDTO.getSubBusinessType();
        // 需要判权的用户id
        String userId = teamVerifyDTO.getUserId();
        // 主数据创建人id
        String creatorId = teamVerifyDTO.getCreatorId();
        // 需要判权的用户/当前操作人
        UserVO loginUser = teamVerifyDTO.getLoginUser();
        // 要添加的负责人
        Set<String> newAddMainUserList = CollectionUtils.isEmpty(teamVerifyDTO.getNewAddMainUserList()) ? new HashSet<>() : teamVerifyDTO.getNewAddMainUserList();
        // 要删除的负责人
//        List<String> newDelMainUserList = teamVerifyDTO.getNewDelMainUserList();
        // 要添加的协同人
        Set<String> newAddCoUserList = CollectionUtils.isEmpty(teamVerifyDTO.getNewAddCoUserList()) ? new HashSet<>() : teamVerifyDTO.getNewAddCoUserList();
        // 要删除的协同人
//        List<String> newDelCoUserList = teamVerifyDTO.getNewDelCoUserList();
        // 是否继承
        Boolean isInheritance = teamVerifyDTO.getIsInheritance();
        // 批量标识
        Integer batchTag = teamVerifyDTO.getBatchTag();
        // 来自退回公海池操作
        Boolean fromBackPublic = teamVerifyDTO.getFromBackPublic();
        Integer operateTag = teamVerifyDTO.getOperateTag();

        TeamAfterVerifyDTO teamAfterVerifyDTO = new TeamAfterVerifyDTO();
        teamAfterVerifyDTO.setLoginUser(loginUser);
        teamAfterVerifyDTO.setCorpid(corpid);
        teamAfterVerifyDTO.setFormId(formId);
        teamAfterVerifyDTO.setSaasMark(saasMark);
        teamAfterVerifyDTO.setBusinessType(businessType);
        teamAfterVerifyDTO.setDistributorMark(distributorMark);
        teamAfterVerifyDTO.setDataId(dataIdIn);
        teamAfterVerifyDTO.setIsInheritance(isInheritance);
        teamAfterVerifyDTO.setFromDetail(teamVerifyDTO.getFromDetail());
        teamAfterVerifyDTO.setFromBackPublic(teamVerifyDTO.getFromBackPublic());
        //下面这个是为了公海池校验的时候用到，现在编辑页需要进行客户公海池捞取频率的校验
        teamAfterVerifyDTO.setIsNew(teamVerifyDTO.getIsNew());
        /*if (CollectionsUtil.isNotEmpty(newAddMainUserList) && CollectionsUtil.isNotEmpty(newAddCoUserList)) {
            teamAfterVerifyDTO.setTeamUserId(newAddMainUserList.get(BasicConstant.ZERO));
        }*/

        // 获取负责人/协同人字段解释
        TeamFieldExplainPOJO teamFieldExplainPOJO = getTeamFieldExplain(corpid, formId, businessType);
        // 负责人解释
        FieldAttrEntity ownerField = teamFieldExplainPOJO.getOwnerField();
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        if (Objects.nonNull(ownerField)) {
            Integer multiple = ownerField.getMultiple();
            if (Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
                if (Objects.isNull(multiple)) {
                    FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
                    if (Objects.nonNull(formOwnerUniqueEnum)) {
                        ownerField.setMultiple(formOwnerUniqueEnum.getValue());
                    }
                }
            }else {
                FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
                if (Objects.nonNull(formOwnerUniqueEnum)) {
                    ownerField.setMultiple(formOwnerUniqueEnum.getValue());
                }
            }
        }

        // 协同人解释
        FieldAttrEntity coUserField = teamFieldExplainPOJO.getCoUserField();
        //协同人可编辑权限
        Integer formPermission = null;
        if (Objects.nonNull(coUserField)) {
            formPermission = coUserField.getFormPermission();
            if (Objects.isNull(formPermission)) {
                formPermission = FormCoUserDefaultPermissionEnum.getDefaultPerByBus(businessType);
            }
        }
        // 离职人员处理,注意现在不管是哪个界面、哪个功能对离职校验都是一样的，都是只有一个负责人，并且这个负责人是离职的，才会提示，其它场景不提示
        Set<String> delUserIdList = new HashSet<> ((Set<String>) CloneUtil.deepClone(newAddMainUserList));
        if (CollectionsUtil.isNotEmpty(newAddCoUserList)) {
            delUserIdList.addAll(newAddCoUserList);
        }
        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, BasicConstant.ONE);
        param.put(ParameterConstant.USER_ID_IN, delUserIdList);
        delUserIdList = new HashSet<>(userModel.getUserIds(param));


        // 共享/隔离处理
        // 获取共享/隔离配置
        FormTeamSetEntity formTeamSetEntity = formTeamSetHelp.getFormTeamSet(corpid, formId, saasMark, businessType, distributorMark);

        // 有共享/隔离的业务
        Integer model = formTeamSetEntity.getModel();
        //非旗舰版套餐默认走通用规则，旗舰版套餐就需要各种判断了。以及未设置过共享或隔离的走默认规则
        if (Objects.isNull(model) || !Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
            model = FormDefaultPatternEnum.getModelValueByBusinessType(businessType);
            formTeamSetEntity.setModel(model);
        }
        Map<String, Set<String>> addMainUserMap = new HashMap<>();
        Map<String, Set<String>> addCoUserMap = new HashMap<>();
        Map<String, Set<String>> delMainUserMap = new HashMap<>();
        Map<String, Set<String>> delCoUserMap = new HashMap<>();
        Map<String, Set<String>> updateMainToCoUserMap = new HashMap<>();
        Map<String, Set<String>> updateCoToMainUserMap = new HashMap<>();


        List<TeamBatchPojo> teamBatchPojos = new ArrayList<>();
        boolean delVerfifyTag = (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark) && Objects.nonNull(ownerField)) ||
                Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark);
        if (teamVerifyDTO.getIsNew()) {
            // 新建
            // 校校验离职人员有个特殊场景，如果负责人中只要有一个员工在职才不校验
            if (delVerfifyTag && CollectionsUtil.isNotEmpty(newAddMainUserList)) {
                Set<String> copyDelAllList = new HashSet<>(((Set<String>) CloneUtil.deepClone(delUserIdList)));
                Set<String> copyDelAddMainUserList = new HashSet<>(((Set<String>) CloneUtil.deepClone(newAddMainUserList)));
                copyDelAddMainUserList.removeAll(copyDelAllList);
                if (CollectionsUtil.isEmpty(copyDelAddMainUserList) || copyDelAddMainUserList.size() == BasicConstant.ZERO) {
                    TeamBatchPojo teamBatchPojo = new TeamBatchPojo();
                    teamBatchPojo.setCode(SystemErrorCodeEnum.API_ERROR_100127.getCode());
                    teamBatchPojo.setFailMsg(I18nMessageUtil.getMessage(TeamMembersConstant.NEW_FAIL_MESSAGE));
                    teamBatchPojo.setFailMsgReason(SystemErrorCodeEnum.API_ERROR_100127.getMsg());
                    teamBatchPojos.add(teamBatchPojo);
                    // 报错直接返回
                    teamAfterVerifyDTO.setTeamBatchPojos(teamBatchPojos);
                    return teamAfterVerifyDTO;
                }
            }
            // 负责人和协同人有重复数据
            if (ExplainUtil.judgeListContainsAnotherListOneValue(new ArrayList<>(newAddMainUserList), new ArrayList<>(newAddCoUserList))) {
                newAddMainUserList.retainAll(newAddCoUserList);

                List<UserEntity> userList = userModel.getByUserIdIn(corpid, newAddMainUserList, true);
                StringBuilder errorUserName = new StringBuilder();
                String errorUser = "";
                for (UserEntity userEntity : userList) {
                    errorUserName.append(userEntity.getName()).append(StringConstant.COMMA);
                }
                if (!errorUserName.toString().isEmpty()) {
                    errorUser = errorUserName.substring(0, errorUserName.length() - 1);
                }

                TeamBatchPojo teamBatchPojo = new TeamBatchPojo();
                teamBatchPojo.setCode(BuinessDefaultErrorCodeEnum.API_ERROR_200024.getCode());
                teamBatchPojo.setFailMsg(I18nMessageUtil.getMessage(TeamMembersConstant.NEW_FAIL_MESSAGE));
                teamBatchPojo.setFailMsgReason(String.format(BuinessDefaultErrorCodeEnum.API_ERROR_200024.getMsg(), errorUser));
                teamBatchPojos.add(teamBatchPojo);

                // 报错直接返回
                teamAfterVerifyDTO.setTeamBatchPojos(teamBatchPojos);
                return teamAfterVerifyDTO;
            }

            for (Long dataId : dataIdIn) {
                if (!teamVerifyDTO.getFromApproval()) {
                    // 不是审批的需要校验
                    // 操作权限校验
                    TeamBatchPojo teamBatchPojo = verifyPermissions(corpid, userId, creatorId, loginUser, newAddMainUserList, null, newAddCoUserList, null, ownerField, coUserField, null, null, isInheritance, fromBackPublic, teamVerifyDTO.getPaasOwnUserFromOwnTag(),
                            null, dataId, operateTag);

                    // 报错处理
                    if (Objects.nonNull(teamBatchPojo)) {
                        teamBatchPojos.add(teamBatchPojo);
                        continue;
                    }
                }

                TeamModelProcessMidPOJO teamModelProcessMidPOJO = new TeamModelProcessMidPOJO(model, corpid, dataId, businessType, newAddMainUserList, null, null, null, newAddCoUserList, null, isInheritance, ownerField, coUserField,
                        new HashSet<>(), new HashSet<>(), loginUser, teamVerifyDTO.getFromDetail(), null, null, null, null, fromBackPublic, operateTag, teamVerifyDTO.getSaasMark(),teamVerifyDTO.getTeamUserId(),teamVerifyDTO.getPlatform(), teamVerifyDTO.getFromCover(), formId);
                // 隔离/共享规则处理
                TeamAfterModeProcessPOJO teamAfterModeProcessPOJO = shareAndIsolationModeProcess(teamModelProcessMidPOJO);
                // 报错处理
                TeamBatchPojo batchPojo = teamAfterModeProcessPOJO.getTeamBatchPojo();
                if (Objects.nonNull(batchPojo)) {
                    teamBatchPojos.add(batchPojo);
                    continue;
                }

                addMainUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getAddMainUserList());
                addCoUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getAddCoUserList());
                teamAfterVerifyDTO.setTeamUserId(teamAfterModeProcessPOJO.getTeamUserId());
            }


        } else {
            // 编辑
            // 获取老的团队数据
            TeamUserListPOJO teamUserListPOJO = getTeamOldUserList(corpid, formId, businessType, subBusinessType, dataIdIn, model);
            // 老的团队所有成员
            Map<Long, Set<String>> oldUserMap = teamUserListPOJO.getOldUserMap();
            // 老的负责人和协同人
            Map<Long, Set<String>> oldMainUserMap = teamUserListPOJO.getOldMainUserMap();
            Map<Long, Set<String>> oldCoUserMap = teamUserListPOJO.getOldCoUserMap();
            //这边需要检验一下离职
            for (Long dataId : dataIdIn) {
                //校验离职人员有个特殊场景，如果负责人中只要有一个员工在职才不校验
                if (delVerfifyTag && CollectionsUtil.isNotEmpty(newAddMainUserList)) {
                    Set<String> copyDelAllList = new HashSet<>(((Set<String>) CloneUtil.deepClone(delUserIdList)));
                    Set<String> copyDelAddMainUserList = new HashSet<>(((Set<String>) CloneUtil.deepClone(newAddMainUserList)));
                    copyDelAddMainUserList.removeAll(copyDelAllList);
                    if (CollectionsUtil.isEmpty(copyDelAddMainUserList) || copyDelAddMainUserList.size() == BasicConstant.ZERO) {
                        TeamBatchPojo teamBatchPojo = new TeamBatchPojo(SystemErrorCodeEnum.API_ERROR_100127.getCode(), SystemErrorCodeEnum.API_ERROR_100127.getMsg(),
                                null, UserTeamOperateTagEnum.TEAM_USER_ALL_OPERATE.getName(), dataId);
                        teamBatchPojos.add(teamBatchPojo);
                        continue;
                    }
                }
                Set<String> oldMainUserList = oldMainUserMap.getOrDefault(dataId, new HashSet<>());
                Set<String> oldCoUserList = oldCoUserMap.getOrDefault(dataId, new HashSet<>());

                Set<String> copyNewAddMainList = new HashSet<>(((Set<String>) CloneUtil.deepClone(newAddMainUserList)));
                // 获得实际添加的负责人
                copyNewAddMainList.removeAll(oldMainUserList);

                Set<String> copyOldMainList = new HashSet<>(((Set<String>) CloneUtil.deepClone(oldMainUserList)));
                // 获得删除的负责人
                copyOldMainList.removeAll(newAddMainUserList);

                Set<String> copyNewCoUserList = new HashSet<>(((Set<String>) CloneUtil.deepClone(newAddCoUserList)));
                // 获得实际要添加的协同人
                copyNewCoUserList.removeAll(oldCoUserList);

                Set<String> copyOldCoUserList =  new HashSet<>(((Set<String>) CloneUtil.deepClone(oldCoUserList)));
                // 获得实际要删除的协同人
                copyOldCoUserList.removeAll(newAddCoUserList);

                Set<String> copyDelCoUserList = new HashSet<>(((Set<String>) CloneUtil.deepClone(copyOldCoUserList)));

                //协同人升级为负责人时,
                if (ExplainUtil.judgeListContainsAnotherListOneValue(new ArrayList<>(copyNewAddMainList), new ArrayList<>(copyOldCoUserList))) {
                    // 获得协同人要升级成负责人的人
                    copyDelCoUserList.retainAll(copyNewAddMainList);
                    // 去除要升级成负责人的人，取得要实际添加的负责人和要删除的协同人
                    copyNewAddMainList.removeAll(copyDelCoUserList);
                    copyOldCoUserList.removeAll(copyDelCoUserList);

                    updateCoToMainUserMap.put(String.valueOf(dataId), copyDelCoUserList);
                }

                Set<String> copyDelMainUserList = new HashSet<>(((Set<String>) CloneUtil.deepClone(copyOldMainList)));
                // 负责人降级为协同人
                if (ExplainUtil.judgeListContainsAnotherListOneValue(new ArrayList<>(copyOldMainList), new ArrayList<>(copyNewCoUserList))) {
                    // 获取降级的人员
                    copyDelMainUserList.retainAll(copyNewCoUserList);
                    // 去除要降级成协同人的人，取得实际要删除的负责人和添加的协同人
                    copyOldMainList.removeAll(copyDelMainUserList);
                    copyNewCoUserList.removeAll(copyDelMainUserList);

                    updateMainToCoUserMap.put(String.valueOf(dataId), copyDelMainUserList);
                }

                // todo 离职人员特殊处理 感觉老逻辑有问题，先这样，测试后再看看

                if (!teamVerifyDTO.getFromApproval()) {
                    // 权限校验
                    TeamBatchPojo teamBatchPojo = verifyPermissions(corpid, userId, creatorId, loginUser, copyNewAddMainList, copyOldMainList, copyNewCoUserList, copyOldCoUserList, ownerField, coUserField, oldMainUserList, oldCoUserList, isInheritance, fromBackPublic, teamVerifyDTO.getPaasOwnUserFromOwnTag(), null, dataId, operateTag);
                    // 报错处理
                    if (Objects.nonNull(teamBatchPojo)) {
                        teamBatchPojos.add(teamBatchPojo);
                        continue;
                    }
                }

                TeamModelProcessMidPOJO teamModelProcessMidPOJO = new TeamModelProcessMidPOJO(model, corpid, dataId, businessType, copyNewAddMainList, updateCoToMainUserMap.getOrDefault(String.valueOf(dataId), new HashSet<>()), updateMainToCoUserMap.getOrDefault(String.valueOf(dataId), new HashSet<>()), copyOldMainList, copyNewCoUserList, copyOldCoUserList, isInheritance, ownerField, coUserField,
                        oldMainUserList, oldCoUserList, loginUser, teamVerifyDTO.getFromDetail(), null, null, null, null, fromBackPublic, operateTag, teamVerifyDTO.getSaasMark(),teamVerifyDTO.getTeamUserId(),teamVerifyDTO.getPlatform(), teamVerifyDTO.getFromCover(), formId);
                // 共享/隔离处理
                TeamAfterModeProcessPOJO teamAfterModeProcessPOJO = shareAndIsolationModeProcess(teamModelProcessMidPOJO);

                // 报错处理
                TeamBatchPojo batchPojo = teamAfterModeProcessPOJO.getTeamBatchPojo();
                if (Objects.nonNull(batchPojo)) {
                    teamBatchPojos.add(batchPojo);
                    continue;
                }

                addMainUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getAddMainUserList());
                delMainUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getDelMainUserList());
                addCoUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getAddCoUserList());
                delCoUserMap.put(String.valueOf(dataId), teamAfterModeProcessPOJO.getDelCoUserList());

            }

        }

        // 公海池规则前置校验
        checkPublicRule(teamVerifyDTO, corpid, businessType, operateTag, addMainUserMap, addCoUserMap, delMainUserMap, delCoUserMap, updateMainToCoUserMap, updateCoToMainUserMap, teamBatchPojos);


        teamAfterVerifyDTO.setTeamBatchPojos(teamBatchPojos);
        teamAfterVerifyDTO.setAddMainUserMap(addMainUserMap);
        teamAfterVerifyDTO.setDelMainUserMap(delMainUserMap);
        teamAfterVerifyDTO.setAddCoUserMap(addCoUserMap);
        teamAfterVerifyDTO.setDelCoUserMap(delCoUserMap);
        teamAfterVerifyDTO.setUpdateToMainUserMap(updateCoToMainUserMap);
        teamAfterVerifyDTO.setUpdateToCoUserMap(updateMainToCoUserMap);
        teamAfterVerifyDTO.setFormTeamSetEntity(formTeamSetEntity);
        teamAfterVerifyDTO.setEditFormPermission(formPermission);
        teamAfterVerifyDTO.setFromCheckRepeatForm(teamVerifyDTO.getFromCheckRepeatForm());
        return teamAfterVerifyDTO;
    }

    /**
     * Description: 团队成员前置校验公海池规则（最大客户数）
     * @param teamVerifyDTO
	 * @param corpid
	 * @param businessType
	 * @param operateTag
	 * @param addMainUserMap
	 * @param addCoUserMap
	 * @param delMainUserMap
	 * @param delCoUserMap
	 * @param updateMainToCoUserMap
	 * @param updateCoToMainUserMap
	 * @param teamBatchPojos
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2022/7/7 17:14
     * @since
     */
    private void checkPublicRule(TeamVerifyDTO teamVerifyDTO, String corpid, Integer businessType, Integer operateTag, Map<String, Set<String>> addMainUserMap, Map<String, Set<String>> addCoUserMap, Map<String, Set<String>> delMainUserMap, Map<String, Set<String>> delCoUserMap, Map<String, Set<String>> updateMainToCoUserMap, Map<String, Set<String>> updateCoToMainUserMap, List<TeamBatchPojo> teamBatchPojos) throws XbbException {
        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            // 客户公海池最大客户数前置校验,高级模式兼容
            CustomerRuleEntity ruleEntity = new CustomerRuleEntity();
            if(commonHelp.isCustomerPublicPoolSeniorModel(corpid)){
                List<TransferBackRuleSeniorEntity> seniorEntityList = transferBackRuleSeniorModel.getTransferBackRuleByType(corpid, null, businessType, Arrays.asList(CustomerSeniorRuleTypeEnum.MAX_CUSTOMER_NUM_RULE.getCode()), BasicConstant.ONE);
                if(CollectionsUtil.isNotEmpty(seniorEntityList)){
                    TransferBackRuleSeniorEntity seniorEntity = seniorEntityList.get(0);
                    ruleEntity.setStatus(seniorEntity.getStatus());
                    ruleEntity.setCorpid(seniorEntity.getCorpid());
                    ruleEntity.setDel(seniorEntity.getDel());
                    ruleEntity.setId(seniorEntity.getId());
                    JSONArray ruleValue = seniorEntity.getRuleValue();
                    if(CollectionsUtil.isNotEmpty(ruleValue)){
                        ruleEntity.setRuleValue(JSON.toJSONString(ruleValue.getJSONObject(0)));
                    }else {
                        ruleEntity.setStatus(BasicConstant.ZERO);
                    }
                }else {
                    ruleEntity.setStatus(BasicConstant.ZERO);
                }
                ruleEntity.setRuleType(CustomerRuleEnum.MAX_CUSTOMER_NUM_RULE.getCode());
            }else {
                ruleEntity = customerRuleModel.getByRuleType(CustomerRuleEnum.MAX_CUSTOMER_NUM_RULE.getCode(), corpid);
            }
            if (Objects.nonNull(ruleEntity)) {
                Map<String, Set<String>> collect = Stream.of(addMainUserMap, updateCoToMainUserMap)
                        .flatMap(v -> v.entrySet().stream())
                        .filter(v -> Objects.nonNull(v.getValue()))
                        .collect(
                            Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                                    (v1, v2) -> Stream.of(v1, v2)
                                    .flatMap(Collection::stream)
                                    .collect(Collectors.toSet()))
                        );
                Map<String, List<UserEntity>> errorMap= new HashMap<>();
                for (Map.Entry<String, Set<String>> entry : collect.entrySet()) {
                    String dataId = entry.getKey();
                    Set<String> userIds = entry.getValue();
                    if (Objects.isNull(userIds)) {
                        continue;
                    }
                    List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, userIds);

                    for (UserEntity userEntity : userEntityList) {
                        boolean flag = checkRuleMaxCustomerNum.canGainCustomer(ruleEntity, corpid, userEntity, Objects.equals(dataId, "null") ? null : Long.valueOf(dataId), BasicConstant.ONE, teamVerifyDTO.getData());
                        if (!flag) {
                            errorMap.computeIfAbsent(dataId, v -> new ArrayList<>()).add(userEntity);
                            addMainUserMap.remove(dataId);
                            addCoUserMap.remove(dataId);
                            delMainUserMap.remove(dataId);
                            delCoUserMap.remove(dataId);
                            updateCoToMainUserMap.remove(dataId);
                            updateMainToCoUserMap.remove(dataId);
                        }
                    }
                }

                if (MapUtils.isNotEmpty(errorMap)) {
                    // 封装错误信息
                    for (Map.Entry<String, List<UserEntity>> entry : errorMap.entrySet()) {
                        String key = entry.getKey();
                        List<UserEntity> value = entry.getValue();

                        TeamBatchPojo teamBatchPojo = new TeamBatchPojo();
                        teamBatchPojo.setCode(UserTeamErrorCodeEnum.API_ERROR_271021.getCode());

                        List<String> businessNameList = value.stream().map(UserEntity::getName).collect(Collectors.toList());

                        if (Objects.equals(UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag(), operateTag)) {
                            teamBatchPojo.setBasicOperate(UserTeamOperateTagEnum.ADD_TEAM_TAG.getName());
                        }else if (Objects.equals(UserTeamOperateTagEnum.DISTRIBUTION.getOperateTag(), operateTag)) {
                            teamBatchPojo.setBasicOperate(UserTeamOperateTagEnum.DISTRIBUTION.getName());
                        }else {
                            teamBatchPojo.setBasicOperate(UserTeamOperateTagEnum.ADD_MAIN.getName());
                        }

                        teamBatchPojo.setDataId(Objects.equals(key, "null") ? null : Long.valueOf(key));
                        teamBatchPojo.setErrorName(teamVerifyDTO.getData().get(CustomerManagementEnum.NAME.getAttr()));
                        teamBatchPojo.setFailMsgReason(String.join(StringConstant.COMMA, businessNameList) +I18nMessageUtil.getMessage(I18nStringConstant.DISSATISFY) + CustomerRuleEnum.MAX_CUSTOMER_NUM_RULE.getName());

                        teamBatchPojos.add(teamBatchPojo);
                    }

                }


            }
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
            // 线索公海池最大线索数前置校验，高级模式兼容
            ClueRuleEntity rule = new ClueRuleEntity();
            if(commonHelp.isCluePublicPoolSeniorModel(corpid)){
                List<TransferBackRuleSeniorEntity> seniorEntityList = transferBackRuleSeniorModel.getTransferBackRuleByType(corpid, null, businessType, Arrays.asList(ClueSeniorRuleTypeEnum.MAX_CLUE_NUM_RULE.getCode()), BasicConstant.ONE);
                if(CollectionsUtil.isNotEmpty(seniorEntityList)){
                    TransferBackRuleSeniorEntity seniorEntity = seniorEntityList.get(0);
                    rule.setStatus(seniorEntity.getStatus());
                    rule.setCorpid(seniorEntity.getCorpid());
                    rule.setDel(seniorEntity.getDel());
                    rule.setId(seniorEntity.getId());
                    JSONArray ruleValue = seniorEntity.getRuleValue();
                    if(CollectionsUtil.isNotEmpty(ruleValue)){
                        rule.setRuleValue(JSON.toJSONString(ruleValue.getJSONObject(0)));
                    }else {
                        rule.setStatus(BasicConstant.ZERO);
                    }
                }else {
                    rule.setStatus(BasicConstant.ZERO);
                }
                rule.setRuleType(ClueRuleEnum.MAX_CLUE_NUM_RULE.getCode());
            }else {
                rule = clueRuleModel.getByRuleType(ClueRuleEnum.MAX_CLUE_NUM_RULE.getCode(), corpid);
            }
            if (Objects.nonNull(rule)) {

                Map<String, Set<String>> collect = Stream.of(addMainUserMap, updateCoToMainUserMap)
                        .flatMap(v -> v.entrySet().stream())
                        .filter(v -> Objects.nonNull(v.getValue()))
                        .collect(
                                Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                                        (v1, v2) -> Stream.of(v1, v2)
                                                .flatMap(Collection::stream)
                                                .collect(Collectors.toSet()))
                        );

                Map<String, List<UserEntity>> errorMap= new HashMap<>();
                for (Map.Entry<String, Set<String>> entry : collect.entrySet()) {
                    String dataId = entry.getKey();
                    Set<String> userIds = entry.getValue();
                    if (Objects.isNull(userIds)) {
                        continue;
                    }
                    List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, userIds);

                    for (UserEntity userEntity : userEntityList) {
                        boolean flag = checkRuleMaxClueNum.canGainClue(rule, corpid, userEntity, Objects.equals(dataId, "null") ? null : Long.valueOf(dataId), BasicConstant.ONE, teamVerifyDTO.getData());
                        if (!flag) {
                            errorMap.computeIfAbsent(dataId, v -> new ArrayList<>()).add(userEntity);
                            addMainUserMap.remove(dataId);
                            addCoUserMap.remove(dataId);
                            delMainUserMap.remove(dataId);
                            delCoUserMap.remove(dataId);
                            updateCoToMainUserMap.remove(dataId);
                            updateMainToCoUserMap.remove(dataId);
                        }
                    }
                }

                if (MapUtils.isNotEmpty(errorMap)) {
                    // 封装错误信息
                    for (Map.Entry<String, List<UserEntity>> entry : errorMap.entrySet()) {
                        String key = entry.getKey();
                        List<UserEntity> value = entry.getValue();

                        TeamBatchPojo teamBatchPojo = new TeamBatchPojo();
                        teamBatchPojo.setCode(UserTeamErrorCodeEnum.API_ERROR_271021.getCode());

                        List<String> businessNameList = value.stream().map(UserEntity::getName).collect(Collectors.toList());

                        if (Objects.equals(UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag(), operateTag)) {
                            teamBatchPojo.setBasicOperate(UserTeamOperateTagEnum.ADD_TEAM_TAG.getName());
                        }else if (Objects.equals(UserTeamOperateTagEnum.DISTRIBUTION.getOperateTag(), operateTag)) {
                            teamBatchPojo.setBasicOperate(UserTeamOperateTagEnum.DISTRIBUTION.getName());
                        }else {
                            teamBatchPojo.setBasicOperate(UserTeamOperateTagEnum.ADD_MAIN.getName());
                        }

                        teamBatchPojo.setDataId(Objects.equals(key, "null") ? null : Long.valueOf(key));
                        teamBatchPojo.setErrorName(teamVerifyDTO.getData().get(ClueEnum.COMPANY_NAME.getAttr()));
                        teamBatchPojo.setFailMsgReason(String.join(StringConstant.COMMA, businessNameList) +I18nMessageUtil.getMessage(I18nStringConstant.DISSATISFY) + ClueRuleEnum.MAX_CLUE_NUM_RULE.getName());

                        teamBatchPojos.add(teamBatchPojo);
                    }

                }

            }

        }
    }



    /**
     * Description: 获取团队相关字段解释
     * @param corpid
     * @param formId
     * @param businessType
     * @return com.xbongbong.pro.team.TeamFieldExplainPOJO
     * @throws
     * @author 魏荣杰
     * @date 2022/1/10 10:11
     * @since
     */
    public TeamFieldExplainPOJO getTeamFieldExplain(String corpid, Long formId, Integer businessType) throws XbbException {
        return proFormHelp.getTeamFieldExplain(corpid, formId, businessType);
    }

    /**
     * Description: 获取操作前的团队数据
     * @param corpid
     * @param formId
     * @param businessType
     * @param subBusinessType
     * @param dataIdIn
     * @param model 有了这个字段下面oldTeamCoUserMap这个才能封装或则不封装，减少代码过滤逻辑
     * @return com.xbongbong.pro.team.TeamUserListPOJO
     * @throws
     * @author 魏荣杰
     * @date 2022/1/10 10:10
     * @since
     */
    public TeamUserListPOJO getTeamOldUserList(String corpid, Long formId, Integer businessType, Integer subBusinessType, List<Long> dataIdIn, Integer model) throws XbbException {
        // 老的团队所有成员
        Map<Long, Set<String>> oldUserMap = new HashMap<>();
        // 老的负责人和协同人以及隔离模式下每个小团队负责人和协同人的对应关系
        Map<Long, Set<String>> oldMainUserMap = new HashMap<>();
        Map<Long, Set<String>> oldCoUsrMap = new HashMap<>();
        Map<Long, Map<String, Set<String>>> oldTeamCoUserMap = new HashMap<>();
        if (UserTeamEnum.hasTeam(businessType)) {
            boolean isPublic = Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(), subBusinessType) || Objects.equals(XbbRefTypeEnum.CLUE_PUBLIC.getCode(), subBusinessType);
            List<UserTeamEntity> userTeamList = getUserTeamList(dataIdIn, corpid, businessType, isPublic);
            for (UserTeamEntity userTeam : userTeamList) {
                oldUserMap.computeIfAbsent(userTeam.getDataId(), v -> new HashSet<>()).add(userTeam.getUserId());
                if (Objects.equals(userTeam.getIsMain(), BasicConstant.ONE)) {
                    oldMainUserMap.computeIfAbsent(userTeam.getDataId(), v -> new HashSet<>()).add(userTeam.getUserId());
                } else {
                    oldCoUsrMap.computeIfAbsent(userTeam.getDataId(), v -> new HashSet<>()).add(userTeam.getUserId());
                }
            }
            if (Objects.equals(model, FormPatternEnum.FORM_ISOLATION.getModel())) {
                for (Map.Entry<Long, Set<String>> entry: oldMainUserMap.entrySet()) {
                    Long dataId = entry.getKey();
                    Set<String> mainUserIdList = entry.getValue();
                    Map<String, Set<String>> teamCoUserMap = new HashMap<>();
                    for (String mainUserId : mainUserIdList) {
                        Set<String> coUserList = new HashSet<>();
                        for (UserTeamEntity userTeamEntity : userTeamList) {
                            if (Objects.nonNull(userTeamEntity.getTeamUserId())
                                    && Objects.equals(mainUserId, userTeamEntity.getTeamUserId()) && Objects.equals(userTeamEntity.getIsMain(), BasicConstant.ZERO)) {
                                coUserList.add(userTeamEntity.getUserId());
                            }
                        }
                        teamCoUserMap.put(mainUserId, coUserList);
                    }
                    oldTeamCoUserMap.put(dataId, teamCoUserMap);
                }
            }
        }

        TeamUserListPOJO teamUserListPOJO = new TeamUserListPOJO();
        teamUserListPOJO.setOldUserMap(oldUserMap);
        teamUserListPOJO.setOldMainUserMap(oldMainUserMap);
        teamUserListPOJO.setOldCoUserMap(oldCoUsrMap);
        teamUserListPOJO.setOldTeamCoUserMap(oldTeamCoUserMap);
        return teamUserListPOJO;
    }

    public List<UserTeamEntity> getUserTeamList (List<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic) {
        return businessUserTeamHelp.getUserTeamList(dataIdList, corpid, businessType, isPublic);
    }

    /**
     * Description: 负责人/协同人操作权限校验
     * @param corpid
     * @param userId
     * @param creatorId
     * @param loginUser
     * @param newAddMainUserList
     * @param newDelMainUserList
     * @param newAddCoUserList
     * @param newDelCoUserList
     * @param ownerField
     * @param coUserField
     * @param oldMainUserList
     * @param oldCoUserList
     * @param isInheritance
     * @param fromBackPublic
     * @param paasOwnUserFromOwnTag
     * @param nameOrSeriNoMap
     * @param dataId
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2022/1/10 14:09
     * @since
     */
    public TeamBatchPojo verifyPermissions(String corpid, String userId, String creatorId, UserVO loginUser, Set<String> newAddMainUserList, Set<String> newDelMainUserList, Set<String> newAddCoUserList, Set<String> newDelCoUserList, FieldAttrEntity ownerField, FieldAttrEntity coUserField, Set<String> oldMainUserList, Set<String> oldCoUserList, Boolean isInheritance, Boolean fromBackPublic,
                                           Boolean paasOwnUserFromOwnTag, Map<Long, String> nameOrSeriNoMap, Long dataId, Integer operateTag) throws XbbException {
        String errorName = Objects.nonNull(nameOrSeriNoMap) ? nameOrSeriNoMap.get(dataId) : null;
        // 继承或者来自退回公海池的操作不进行字段权限校验
        if (isInheritance || fromBackPublic) {
            return null;
        }

        TeamBatchPojo teamBatchPojo = null;
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        if (Objects.isNull(userEntity)) {
            teamBatchPojo = new TeamBatchPojo();
            teamBatchPojo.setCode(SystemErrorCodeEnum.API_ERROR_100004.getCode());
            teamBatchPojo.setDataId(dataId);
            commonHelp.singleFailMsg(errorName, UserTeamOperateTagEnum.TEAM_USER_ALL_OPERATE.getName(), teamBatchPojo);
            teamBatchPojo.setFailMsgReason(SystemErrorCodeEnum.API_ERROR_100004.getMsg());
            return teamBatchPojo;
        }
        List<String> subIdList = userModel.getManageUser(userEntity);

        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        handlerExplainDTO.setUserId(userId);
        handlerExplainDTO.setCreatorId(creatorId);
        handlerExplainDTO.setCoUserId(CollectionUtils.isEmpty(oldCoUserList) ? new ArrayList<>() : new ArrayList<>(oldCoUserList));
        handlerExplainDTO.setOwnerId(CollectionUtils.isEmpty(oldMainUserList) ? new ArrayList<>() : new ArrayList<>(oldMainUserList));
        handlerExplainDTO.setSubIdList(subIdList);
        handlerExplainDTO.setLoginUser(loginUser);


        // 添加/删除负责人权限判断
        if (CollectionUtils.isNotEmpty(newAddMainUserList)) {
            //paas表单只有拖进负责人字段并且负责人字段有值才需要校验，否则不需要校验，因为强制用创建人id作为负责人id
            if (paasOwnUserFromOwnTag) {
                if (Objects.nonNull(ownerField)) {
                    Boolean havePermission = ExplainUtil.advancedOperationHavePermission(ownerField, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
                    if (!havePermission) {
                        teamBatchPojo = new TeamBatchPojo();
                        teamBatchPojo.setCode(UserTeamErrorCodeEnum.API_ERROR_390007.getCode());
                        if (Objects.equals(UserTeamOperateTagEnum.ADD_TEAM_TAG.getOperateTag(), operateTag)) {
                            commonHelp.singleFailMsg(errorName, UserTeamOperateTagEnum.ADD_TEAM_TAG.getName(), teamBatchPojo);
                        }else if (Objects.equals(UserTeamOperateTagEnum.DISTRIBUTION.getOperateTag(), operateTag)) {
                            commonHelp.singleFailMsg(errorName, UserTeamOperateTagEnum.DISTRIBUTION.getName(), teamBatchPojo);
                        }else {
                            commonHelp.singleFailMsg(errorName, UserTeamOperateTagEnum.ADD_MAIN.getName(), teamBatchPojo);
                        }
                        teamBatchPojo.setDataId(dataId);
                        teamBatchPojo.setFailMsgReason(UserTeamErrorCodeEnum.API_ERROR_390007.getMsg());
                        return teamBatchPojo;
                    }
                }
            }
        }

        if (CollectionUtils.isNotEmpty(newDelMainUserList)) {
            if (Objects.nonNull(ownerField)) {
                Boolean havePermission = ExplainUtil.advancedOperationHavePermission(ownerField, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
                if (!havePermission) {
                    teamBatchPojo = new TeamBatchPojo();
                    teamBatchPojo.setCode(UserTeamErrorCodeEnum.API_ERROR_390005.getCode());
                    if (Objects.equals(UserTeamOperateTagEnum.DEL_TEAM_TAG.getOperateTag(), operateTag)) {
                        commonHelp.singleFailMsg(errorName, UserTeamOperateTagEnum.DEL_TEAM_TAG.getName(), teamBatchPojo);
                    }else {
                        commonHelp.singleFailMsg(errorName, UserTeamOperateTagEnum.DEL_MAIN.getName(), teamBatchPojo);
                    }
                    teamBatchPojo.setDataId(dataId);
                    teamBatchPojo.setFailMsgReason(UserTeamErrorCodeEnum.API_ERROR_390005.getMsg());
                    return teamBatchPojo;
                }
            }
        }

        // 添加/删除协同人权限判断
        if (CollectionUtils.isNotEmpty(newAddCoUserList)) {
            if (Objects.nonNull(coUserField)) {
                Boolean havePermission = ExplainUtil.advancedOperationHavePermission(coUserField, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
                if (!havePermission) {
                    teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_390008.getCode(), UserTeamErrorCodeEnum.API_ERROR_390008.getMsg(), errorName, UserTeamOperateTagEnum.ADD_COUSER.getName(),
                            dataId);
                    return teamBatchPojo;
                }
            }
        }

        if (CollectionUtils.isNotEmpty(newDelCoUserList)) {
            if (Objects.nonNull(coUserField)) {
                Boolean havePermission = ExplainUtil.advancedOperationHavePermission(coUserField, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
                if (!havePermission) {
                    teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_390006.getCode(), UserTeamErrorCodeEnum.API_ERROR_390006.getMsg(), errorName,
                            UserTeamOperateTagEnum.DEL_COUSER.getName(), dataId);
                }
            }
        }
        return teamBatchPojo;
    }


    /**
     * Description: 共享/隔离模式业务处理
     * @return com.xbongbong.pro.team.TeamAfterVerifyDTO
     * @throws
     * @author 魏荣杰
     * @date 2022/1/12 16:03
     * @since
     */
    public TeamAfterModeProcessPOJO shareAndIsolationModeProcess(TeamModelProcessMidPOJO teamModelProcessMidPOJO) throws XbbException {
        TeamAfterModeProcessPOJO teamAfterModeProcessPOJO = new TeamAfterModeProcessPOJO();
        String teamUserId = teamModelProcessMidPOJO.getTeamUserId();
        teamAfterModeProcessPOJO.setTeamUserId(teamUserId);
        String corpid = teamModelProcessMidPOJO.getCorpid();
        Integer model = teamModelProcessMidPOJO.getModel();
        Integer businessType = teamModelProcessMidPOJO.getBusinessType();
        Integer saasMark = teamModelProcessMidPOJO.getSaasMark();
        Long formId = teamModelProcessMidPOJO.getFormId();
        Long dataId = teamModelProcessMidPOJO.getDataId();
        Boolean isInheritance = teamModelProcessMidPOJO.getIsInheritance();
        Set<String> newAddMainUserList = teamModelProcessMidPOJO.getNewAddMainUserList();
        Set<String> newAddCoUserList = teamModelProcessMidPOJO.getNewAddCoUserList();
        Set<String> oldCoUserList = teamModelProcessMidPOJO.getOldCoUserList();
        Set<String> oldMainUserList = teamModelProcessMidPOJO.getOldMainUserList();
        Set<String> oldTeam = Streams.concat(oldCoUserList.stream(), oldMainUserList.stream()).collect(Collectors.toSet());
        Set<String> newDelMainUserList = teamModelProcessMidPOJO.getNewDelMainUserList();
        Set<String> newDelCoUserList = teamModelProcessMidPOJO.getNewDelCoUserList();
        FieldAttrEntity ownerField = teamModelProcessMidPOJO.getOwnerField();
        FieldAttrEntity coUserField = teamModelProcessMidPOJO.getCoUserField();
        UserVO loginUser = teamModelProcessMidPOJO.getLoginUser();
        String originUserId = teamModelProcessMidPOJO.getOriginUserId();
        String changeUserId = teamModelProcessMidPOJO.getChangeUserId();
        Set<String> updateCoToMainUserList = teamModelProcessMidPOJO.getUpdateCoToMainUserList();
        Set<String> updateMainToCoUserList = teamModelProcessMidPOJO.getUpdateMainToCoUserList();
        Map<Long, String> nameOrSeriNoMap = Objects.nonNull(teamModelProcessMidPOJO.getNameOrSeriNoMap()) ? teamModelProcessMidPOJO.getNameOrSeriNoMap() : new HashMap<>();
        Map<String, Set<String>> oldTeamCoUserRelMap = teamModelProcessMidPOJO.getOldTeamCoUserRelMap();
        Boolean fromBackPublic = teamModelProcessMidPOJO.getFromBackPublic();
        //只有是隔离模式并且是客户、线索业务才会走真正的隔离操作；特殊逻辑：合并客户统一按共享模式进行校验
        boolean specialBusinessType = Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.CLUE.getCode(), businessType);
        boolean trueIsloationModel = Objects.equals(model, FormPatternEnum.FORM_ISOLATION.getModel()) && specialBusinessType
                && !Objects.equals(OperateTypeEnum.CUSTOMER_MERGE.getCode(), teamModelProcessMidPOJO.getOperateTag());
        if (!trueIsloationModel) {
            // 共享
            if (CollectionUtils.isNotEmpty(newAddMainUserList)) {
                // 添加负责人
                // 判断是否在团队中
                TeamBatchPojo teamBatchPojo = checkInTeamForAdd(oldTeam, newAddMainUserList, corpid, nameOrSeriNoMap.get(dataId), UserTeamOperateTagEnum.ADD_MAIN, dataId);
                //来自继承的下游的业务，若团队中存在相同人员也不用抛异常，去掉重复人员继续操作即可
                if (!Objects.equals(UserTeamOperateTagEnum.HANDOVER.getOperateTag(), teamModelProcessMidPOJO.getOperateTag()) && Objects.nonNull(teamBatchPojo) && !isInheritance) {
                    teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                    return teamAfterModeProcessPOJO;
                }
                // 去除已经在团队中的数据
                Set<String> copyList = new HashSet<>((Set<String>) CloneUtil.deepClone(newAddMainUserList));
                copyList.removeAll(oldTeam);
                if (!Objects.isNull(ownerField)) {
                    if (teamModelProcessMidPOJO.getIsInheritance()) {
                        Integer multiple = ownerField.getMultiple();
                        // 如果是继承才需要去判断负责人唯一情况，如果触发的数据是负责人唯一的情况是不能添加负责人的
                        if (Objects.equals(multiple, BasicConstant.ONE)) {
                            //移交继承的时候，如果下游业务是协同人变成负责人的情况，那么就不是删除负责人，而是协同人变成负责人之后，流程结束
                            //这边分两种情况，第一种是移交给的人在协同人里面，被移交的人在负责人里面；这种情况的话是协同人转负责人，然后删除被移交的负责人
                            //第二种情况是移交的人在协同人里面，但是被移交的人不在负责人里面；这时候并不是新增一个负责人然后删除一个负责人，这样的话移交啥都没操作，只能赋值于协同人转负责任人
                            if (Objects.equals(UserTeamOperateTagEnum.HANDOVER.getOperateTag(), teamModelProcessMidPOJO.getOperateTag())
                                        && oldCoUserList.contains(newAddMainUserList.stream().findFirst().get())) {
                                teamAfterModeProcessPOJO.setCoToMainUserList(newAddMainUserList);
                                if (oldMainUserList.contains(newDelMainUserList.stream().findFirst().get())) {
                                    teamAfterModeProcessPOJO.setDelMainUserList(newDelMainUserList);
                                }
                                return teamAfterModeProcessPOJO;
                            } else {
                                // 不唯一
                                // 获得要添加的负责人
                                teamAfterModeProcessPOJO.setAddMainUserList(copyList);
                            }
                        } else {
                            // 唯一
                            if (CollectionUtils.isNotEmpty(oldMainUserList)) {
                                if (Objects.equals(UserTeamOperateTagEnum.HANDOVER.getOperateTag(), teamModelProcessMidPOJO.getOperateTag())) {
                                    //第一种：老的协同人包含新移交的人=》（1）老的负责人包含需要删除的人，协同人变成负责人,老负责人删除
                                    //                             （2）老的负责人不包含需要删除的人，这时候啥都不操作，直接返回
                                    //第二种：老的协同人不包含新移交的人=》（1）老的负责人包含需要删除的人，老负责人删除，新增负责人
                                    //                           => (2) 老的负责人不包含需要删除的人，不需要删除负责人，新增协同人
                                    if (oldCoUserList.contains(newAddMainUserList.stream().findFirst().get())) {
                                        if (oldMainUserList.contains(newDelMainUserList.stream().findFirst().get())) {
                                            teamAfterModeProcessPOJO.setCoToMainUserList(newAddMainUserList);
                                            teamAfterModeProcessPOJO.setDelMainUserList(newDelMainUserList);
                                        }
                                    }else {
                                        if (oldMainUserList.contains(newDelMainUserList.stream().findFirst().get())) {
                                            teamAfterModeProcessPOJO.setAddMainUserList(copyList);
                                            teamAfterModeProcessPOJO.setDelMainUserList(newDelMainUserList);
                                        }else {
                                            teamAfterModeProcessPOJO.setAddCoUserList(copyList);
                                        }
                                    }
                                    return teamAfterModeProcessPOJO;
                                }else {
                                    // 如果已经有负责人将这些负责人变成要加的协同人
                                    teamAfterModeProcessPOJO.setAddCoUserList(copyList);
                                }
                            } else {
                                // 获得要添加的负责人
                                if (copyList.size() == 1) {
                                    teamAfterModeProcessPOJO.setAddMainUserList(copyList);
                                } else if (copyList.size() > 1 ) {
                                    Set<String> set = new HashSet<>(Collections.singletonList(copyList.stream().findFirst().get()));
                                    teamAfterModeProcessPOJO.setAddMainUserList(set);
                                    copyList.removeAll(set);
                                    teamAfterModeProcessPOJO.setAddCoUserList(copyList);
                                }
                            }
                        }
                    } else {
                        Integer multiple = ownerField.getMultiple();
                        if (Objects.equals(multiple, BasicConstant.ONE)) {
                            // 不唯一
                            // 获得要添加的负责人
                            teamAfterModeProcessPOJO.setAddMainUserList(copyList);
                        } else {
                            // 唯一
                            Set<String> oLdMainCopy = new HashSet<>();
                            if (Objects.nonNull(oldMainUserList)) {
                                oLdMainCopy = (Set<String>) CloneUtil.deepClone(oldMainUserList);
                            }
                            if (Objects.nonNull(newDelMainUserList)) {
                                oLdMainCopy.removeAll(newDelMainUserList);
                            }
                            if (Objects.nonNull(updateMainToCoUserList)) {
                                oLdMainCopy.removeAll(updateMainToCoUserList);
                            }
                            if (CollectionsUtil.isNotEmpty(oLdMainCopy) && CollectionsUtil.isNotEmpty(copyList)) {
                                // 唯一有负责人数据情况，要报错
                                TeamBatchPojo pojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271032.getCode(), UserTeamErrorCodeEnum.API_ERROR_271032.getMsg(),
                                        nameOrSeriNoMap.get(dataId), UserTeamOperateTagEnum.ADD_MAIN.getName(), dataId);
                                teamAfterModeProcessPOJO.setTeamBatchPojo(pojo);
                                return teamAfterModeProcessPOJO;
                            } else {
                                if (copyList.size() > BasicConstant.ONE) {
                                    // 如果设置了唯一但是是多个，报错
                                    TeamBatchPojo pojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271015.getCode(), UserTeamErrorCodeEnum.API_ERROR_271015.getMsg(),
                                            nameOrSeriNoMap.get(dataId), UserTeamOperateTagEnum.ADD_MAIN.getName(), dataId);
                                    teamAfterModeProcessPOJO.setTeamBatchPojo(pojo);
                                    return teamAfterModeProcessPOJO;
                                }
                                // 获得要添加的负责人
                                teamAfterModeProcessPOJO.setAddMainUserList(copyList);
                            }
                        }

                    }
                } else if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark)) {
                    // 没有设置负责人字段不处理,但是paas表单没有负责人的时候用创建人作为负责人
                    teamAfterModeProcessPOJO.setAddMainUserList(copyList);
                }

            }
            if (CollectionUtils.isNotEmpty(newDelMainUserList)) {
                // 删除负责人
                // 判断是否在负责团队中
                TeamBatchPojo pojo = checkInTeamForDel(oldMainUserList, newDelMainUserList, corpid, nameOrSeriNoMap.get(dataId), UserTeamOperateTagEnum.DEL_MAIN, dataId);
                if (!Objects.equals(UserTeamOperateTagEnum.HANDOVER.getOperateTag(), teamModelProcessMidPOJO.getOperateTag()) && Objects.nonNull(pojo) && !isInheritance) {
                    teamAfterModeProcessPOJO.setTeamBatchPojo(pojo);
                    return teamAfterModeProcessPOJO;
                }
                Set<String> copyList = new HashSet<> ((Set<String>) CloneUtil.deepClone(oldMainUserList));
                copyList.removeAll(newDelMainUserList);
                if(CollectionUtils.isNotEmpty(newAddMainUserList)){
                    copyList.addAll(newAddMainUserList);
                }
                if(CollectionUtils.isNotEmpty(updateCoToMainUserList)){
                    copyList.addAll(updateCoToMainUserList);
                }
                //特殊逻辑：联系人表单的负责人删除受负责人字段唯一属性控制，其它业务还是按照照常逻辑走
                if (Objects.equals(XbbRefTypeEnum.CONTACT.getCode(), businessType)) {
                    Integer required = ownerField.getRequired();
                    if (Objects.equals(BasicConstant.ONE, required) && CollectionUtils.isEmpty(copyList)) {
                        // 至少保留一个负责人
                        String errorName = nameOrSeriNoMap.get(dataId);
                        TeamBatchPojo teamBatchPojo = new TeamBatchPojo(BuinessDefaultErrorCodeEnum.API_ERROR_200016.getCode(), BuinessDefaultErrorCodeEnum.API_ERROR_200016.getMsg(),
                                errorName, UserTeamOperateTagEnum.DEL_MAIN.getName(), dataId);
                        teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                        return teamAfterModeProcessPOJO;
                    }
                } else if (!teamModelProcessMidPOJO.getIsInheritance() && !teamModelProcessMidPOJO.getFromBackPublic() && !teamModelProcessMidPOJO.getFromCover()) {
                    // 非继承,公海池退回的时候需要判断一下某些业务负责人数量
                    if ((Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.CLUE.getCode(), businessType)) && !teamModelProcessMidPOJO.getFromDetail()) {
                        // 从详情页操作，并且是客户，线索业务不做校验

                    } else if (CollectionUtils.isEmpty(copyList) && Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
                        // 至少保留一个负责人
                        String errorName = nameOrSeriNoMap.get(dataId);
                        TeamBatchPojo teamBatchPojo = new TeamBatchPojo(BuinessDefaultErrorCodeEnum.API_ERROR_200016.getCode(), BuinessDefaultErrorCodeEnum.API_ERROR_200016.getMsg(),
                                errorName, UserTeamOperateTagEnum.DEL_MAIN.getName(), dataId);
                        teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                        return teamAfterModeProcessPOJO;
                    }
                }
                // 获取要删除的负责人
                teamAfterModeProcessPOJO.setDelMainUserList(newDelMainUserList);

            }
            if (CollectionUtils.isNotEmpty(newAddCoUserList)) {
                // 添加协同人
                // 判断是否在团队中
                TeamBatchPojo teamBatchPojo = checkInTeamForAdd(oldTeam, newAddCoUserList, corpid, nameOrSeriNoMap.get(dataId), UserTeamOperateTagEnum.ADD_COUSER, dataId);
                //来自继承的下游的业务，若团队中存在相同人员也不用抛异常，去掉重复人员继续操作即可
                if (Objects.nonNull(teamBatchPojo) && !isInheritance) {
                    teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                    return teamAfterModeProcessPOJO;
                }
                // 去除已经在协同人中的数据
                Set<String> copyList = new HashSet<> ((Set<String>) CloneUtil.deepClone(newAddCoUserList));
                copyList.removeAll(oldTeam);
                if (!Objects.isNull(coUserField) || Objects.equals(XbbRefTypeEnum.PREPAY_BALANCE.getCode(), businessType)
                        || Objects.equals(XbbRefTypeEnum.PREPAY.getCode(), businessType)) {
                    // 获得要添加的协同人
                    // 预收款跟预付款没有团队
                    if (Objects.isNull(teamAfterModeProcessPOJO.getAddCoUserList())) {
                        teamAfterModeProcessPOJO.setAddCoUserList(copyList);
                    } else {
                        teamAfterModeProcessPOJO.getAddCoUserList().addAll(copyList);
                    }
                } else {
                    // 没有设置协同人字段不处理
                }

            }
            if (CollectionUtils.isNotEmpty(newDelCoUserList)) {
                // 删除协同人
                // 判断是否在协同团队中
                TeamBatchPojo pojo = checkInTeamForDel(oldCoUserList, newDelCoUserList, corpid, nameOrSeriNoMap.get(dataId), UserTeamOperateTagEnum.DEL_COUSER, dataId);
                if (!Objects.equals(UserTeamOperateTagEnum.HANDOVER.getOperateTag(), teamModelProcessMidPOJO.getOperateTag()) && Objects.nonNull(pojo) && !isInheritance) {
                    teamAfterModeProcessPOJO.setTeamBatchPojo(pojo);
                    return teamAfterModeProcessPOJO;
                }
                // 获取要删除的协同人
                teamAfterModeProcessPOJO.setDelCoUserList(newDelCoUserList);
            }
            //移交负责人相关逻辑判断
            if (Objects.nonNull(changeUserId)) {
                shareHandleOver(originUserId, changeUserId, teamAfterModeProcessPOJO, dataId, nameOrSeriNoMap, oldMainUserList,
                        newDelMainUserList, oldCoUserList, newAddMainUserList, newDelCoUserList, teamModelProcessMidPOJO.getPlatform());
            }

        } else {
            // 隔离
            if (!fromBackPublic) {
                boolean adminOrBossTag = loginUser.isAdminOrBoss();
                //隔离模式下并且当前人原非超管，只允许添加一个负责人
                if (!adminOrBossTag && CollectionsUtil.isNotEmpty(newAddMainUserList) && newAddMainUserList.size() > BasicConstant.ONE) {
                    TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271002.getCode(), UserTeamErrorCodeEnum.API_ERROR_271002.getMsg(),
                            nameOrSeriNoMap.get(dataId), UserTeamOperateTagEnum.ADD_MAIN.getName(), dataId);
                    teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                    return teamAfterModeProcessPOJO;
                }
            }
            if (CollectionUtils.isNotEmpty(newAddMainUserList)) {
                // 判断是否在团队中
                TeamBatchPojo teamBatchPojo = checkInTeamForAdd(oldTeam, newAddMainUserList, corpid, nameOrSeriNoMap.get(dataId), UserTeamOperateTagEnum.ADD_MAIN, dataId);
                if (Objects.nonNull(teamBatchPojo)) {
                    teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                    return teamAfterModeProcessPOJO;
                }
                // 去除已经在负责人中的数据
                newAddMainUserList.removeAll(oldMainUserList);

                if (Objects.nonNull(ownerField)) {
                    Integer multiple = ownerField.getMultiple();
                    if (Objects.equals(multiple, BasicConstant.ONE)) {
                        //不唯一
                        // 获得要添加的团队
                        teamAfterModeProcessPOJO.setAddMainUserList(newAddMainUserList);
                    } else {
                        // 唯一
                        Set<String> oLdMainCopy = new HashSet<>();
                        if (Objects.nonNull(oldMainUserList)) {
                            oLdMainCopy = (Set<String>) CloneUtil.deepClone(oldMainUserList);
                        }
                        if (Objects.nonNull(newDelMainUserList)) {
                            oLdMainCopy.removeAll(newDelMainUserList);
                        }
                        if (Objects.nonNull(updateMainToCoUserList)) {
                            oLdMainCopy.removeAll(updateMainToCoUserList);
                        }
                        if (CollectionsUtil.isNotEmpty(oLdMainCopy) && CollectionsUtil.isNotEmpty(newAddMainUserList)) {
                            // 唯一有负责人数据情况，要报错
                            TeamBatchPojo pojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271032.getCode(), UserTeamErrorCodeEnum.API_ERROR_271032.getMsg(),
                                    nameOrSeriNoMap.get(dataId), UserTeamOperateTagEnum.ADD_MAIN.getName(), dataId);
                            teamAfterModeProcessPOJO.setTeamBatchPojo(pojo);
                            return teamAfterModeProcessPOJO;
                        } else {
                            if (newAddMainUserList.size() > 1) {
                                // 如果设置了唯一但是是多个，报错
                                TeamBatchPojo pojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271015.getCode(), UserTeamErrorCodeEnum.API_ERROR_271015.getMsg(),
                                        nameOrSeriNoMap.get(dataId), UserTeamOperateTagEnum.ADD_MAIN.getName(), dataId);
                                teamAfterModeProcessPOJO.setTeamBatchPojo(pojo);
                                return teamAfterModeProcessPOJO;
                            }
                            // 获得要添加的团队
                            teamAfterModeProcessPOJO.setAddMainUserList(newAddMainUserList);
                        }
                    }
                } else {
                    // 没有设置负责人字段不处理
                }

            }
            if (CollectionUtils.isNotEmpty(newDelMainUserList)) {
                if(!oldMainUserList.contains(newDelMainUserList.stream().findFirst().get())){
                    //所选的负责人的团队不存在
                    List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, Collections.singletonList(newDelMainUserList.stream().findFirst().get()), true);
                    String userName = userEntityList.get(Constant.ZERO).getName();
                    String errorName = nameOrSeriNoMap.get(dataId);
                    TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271009.getCode(), String.format(UserTeamErrorCodeEnum.API_ERROR_271009.getMsg(),userName),
                            errorName, UserTeamOperateTagEnum.DEL_TEAM_TAG.getName(), dataId);
                    teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                    return teamAfterModeProcessPOJO;
                }
                // 解散团队
                Set<String> copyList = new HashSet<>((Set<String>) CloneUtil.deepClone(oldMainUserList));
                copyList.removeAll(newDelMainUserList);
                if(CollectionUtils.isNotEmpty(newAddMainUserList)){
                    copyList.addAll(newAddMainUserList);
                }
                if(CollectionUtils.isNotEmpty(updateCoToMainUserList)){
                    copyList.addAll(updateCoToMainUserList);
                }
                // 非继承,公海池退回的时候需要判断一下某些业务负责人数量
                if (!teamModelProcessMidPOJO.getIsInheritance() && !teamModelProcessMidPOJO.getFromBackPublic() && !teamModelProcessMidPOJO.getFromCover()) {
                    if (CollectionUtils.isEmpty(copyList) && Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
                        // 至少保留一个团队
                        //解散团队从列表页或者tab页过来。都是单选的
                        String errorName = nameOrSeriNoMap.get(dataId);
                        TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271014.getCode(), UserTeamErrorCodeEnum.API_ERROR_271014.getMsg(),
                                errorName, UserTeamOperateTagEnum.DEL_TEAM_TAG.getName(), dataId);
                        teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                        return teamAfterModeProcessPOJO;
                    }
                }
                // 要删除的协同人
                Map<String, Object> param = new HashMap<>();
                param.put(ParameterConstant.CORPID, corpid);
                param.put("teamUserIdIn", newDelMainUserList);
                param.put(ParameterConstant.IS_MAIN, BasicConstant.ZERO);
                List<UserTeamEntity> coUserList = businessUserTeamHelp.getUserTeamListByParams(Collections.singletonList(dataId), businessType, param);

                Set<String> coUserDelList = coUserList.stream().map(UserTeamEntity::getUserId).collect(Collectors.toSet());

                teamAfterModeProcessPOJO.setDelMainUserList(newDelMainUserList);
                teamAfterModeProcessPOJO.setDelCoUserList(coUserDelList);
            }
            if (CollectionUtils.isNotEmpty(newAddCoUserList)) {
                if(Objects.isNull(teamUserId)){
                    //隔离模式添加协同人，一定要选择负责人
                    String errorName = nameOrSeriNoMap.get(dataId);
                    TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271034.getCode(),UserTeamErrorCodeEnum.API_ERROR_271034.getMsg(),
                            errorName, UserTeamOperateTagEnum.ADD_COUSER.getName(), dataId);
                    teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                    return teamAfterModeProcessPOJO;
                }
                if(StringUtil.isNotEmpty(teamUserId) && !oldMainUserList.contains(teamUserId)){
                    //所选的负责人的团队不存在
                    List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, Collections.singletonList(teamUserId), true);
                    String userName = userEntityList.get(Constant.ZERO).getName();
                    String errorName = nameOrSeriNoMap.get(dataId);
                    TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271009.getCode(), String.format(UserTeamErrorCodeEnum.API_ERROR_271009.getMsg(),userName),
                            errorName, UserTeamOperateTagEnum.ADD_COUSER.getName(), dataId);
                    teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                    return teamAfterModeProcessPOJO;
                }
                // 判断是否在团队中
                TeamBatchPojo teamBatchPojo = checkInTeamForAdd(oldTeam, newAddCoUserList, corpid, nameOrSeriNoMap.get(dataId), UserTeamOperateTagEnum.ADD_COUSER, dataId);
                if (Objects.nonNull(teamBatchPojo)) {
                    teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                    return teamAfterModeProcessPOJO;
                }
                // 去除已经在协同人中的数据
                newAddCoUserList.removeAll(oldCoUserList);
                if (!Objects.isNull(coUserField)) {
                    // 获得要添加的协同人
                    teamAfterModeProcessPOJO.setAddCoUserList(newAddCoUserList);
                    //下面这种情况主要是为了兼容低权限的人在新增界面新增负责人、协同人的场景
                    if (StringUtil.isEmpty(teamUserId) && CollectionUtils.isNotEmpty(newAddMainUserList)) {
                        teamAfterModeProcessPOJO.setTeamUserId(new ArrayList<>(newAddMainUserList).get(BasicConstant.ZERO));
                    }
                    //teamAfterModeProcessPOJO.setTeamUserId(newAddMainUserList.stream().findFirst().get());
                    //teamAfterModeProcessPOJO.setTeamUserId(teamUserId);
                } else {
                    // 没有设置协同人字段不处理

                }

            }
            if (CollectionUtils.isNotEmpty(newDelCoUserList)) {
                //String teamUserId = teamModelProcessMidPOJO.getTeamUserId();
                //批量过来的会传teamUserId，若选择的负责人团队不存在则报错

                if(StringUtil.isNotEmpty(teamUserId) && !oldMainUserList.contains(teamUserId) ){
                    //所选的负责人的团队不存在
                    List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, Collections.singletonList(teamUserId), true);
                    String userName = userEntityList.get(Constant.ZERO).getName();
                    String errorName = nameOrSeriNoMap.get(dataId);
                    TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271009.getCode(), String.format(UserTeamErrorCodeEnum.API_ERROR_271009.getMsg(),userName),
                            errorName, UserTeamOperateTagEnum.ADD_COUSER.getName(), dataId);
                    teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                    return teamAfterModeProcessPOJO;
                }
                if(!oldCoUserList.contains(newDelCoUserList.stream().findFirst().get())) {
                    //所删人员不在该团队中
                    List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, Collections.singletonList(newDelCoUserList.stream().findFirst().get()), true);
                    String userName = userEntityList.get(Constant.ZERO).getName();
                    String errorName = nameOrSeriNoMap.get(dataId);
                    TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271012.getCode(), String.format(UserTeamErrorCodeEnum.API_ERROR_271012.getMsg(),userName),
                            errorName, UserTeamOperateTagEnum.DEL_COUSER.getName(), dataId);
                    teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                    return teamAfterModeProcessPOJO;
                }

                if(StringUtil.isNotEmpty(teamUserId)){
                    Set<String> coSet = oldTeamCoUserRelMap.get(teamUserId);
                    //批量删除某团队的协同人，其中有协同人不在所选负责人团队中
                    if(CollectionUtils.isEmpty(coSet) || !coSet.containsAll(newDelCoUserList)){
                        Map<String, UserEntity> userEntityMap = userModel.getByUserIdIn(corpid, newDelCoUserList, true).stream().collect(Collectors.toMap(UserEntity::getUserId, v -> v));
                        Set<String> notExistList;
                        if(CollectionUtils.isEmpty(coSet)){
                            notExistList = newDelCoUserList;
                        }else{
                            notExistList = newDelCoUserList.stream().filter(v -> !coSet.contains(v)).collect(Collectors.toSet());
                        }
                        if(CollectionUtils.isNotEmpty(notExistList)){
                            StringBuilder errorUserName = new StringBuilder();
                            for (String userId : notExistList) {
                                errorUserName.append(userEntityMap.get(userId).getName()).append(StringConstant.COMMA);
                            }
                            errorUserName.deleteCharAt(errorUserName.length()-1);
                            String errorName = nameOrSeriNoMap.get(dataId);
                            TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271012.getCode(), String.format(UserTeamErrorCodeEnum.API_ERROR_271012.getMsg(),errorUserName),
                                    errorName, UserTeamOperateTagEnum.DEL_COUSER.getName(), dataId);
                            teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
                            return teamAfterModeProcessPOJO;
                        }

                    }
                }

                // 删除协同人
                // 获得要删除的协同人
                teamAfterModeProcessPOJO.setDelCoUserList(newDelCoUserList);
            }
            if (Objects.nonNull(originUserId) && Objects.nonNull(changeUserId)) {
                isolationHandleOver(corpid, originUserId, changeUserId, dataId, nameOrSeriNoMap, teamAfterModeProcessPOJO,
                        newDelMainUserList, newAddMainUserList, oldMainUserList, oldCoUserList, oldTeamCoUserRelMap, loginUser, saasMark, businessType, formId);
            }
        }
        return teamAfterModeProcessPOJO;
    }

    /**
     * Description: 判断要新增的人员是否已经在团队中（增加负责人不能在协同人中，增加协同人不能在负责人中）在tab中操作使用
     * @param oldUserList
     * @param newAddUserList
     * @param corpid
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2021/12/30 22:25
     * @since
     */
    private TeamBatchPojo checkInTeamForAdd(Set<String> oldUserList, Set<String> newAddUserList, String corpid, String errorName, UserTeamOperateTagEnum userTeamOperateTagEnum, Long dataId) throws XbbException {
        TeamBatchPojo teamBatchPojo = null;
        oldUserList.retainAll(newAddUserList);
        if (CollectionUtils.isNotEmpty(oldUserList)) {
            List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, oldUserList, true);
            if (CollectionsUtil.isEmpty(userEntityList)) {
                return teamBatchPojo;
            }
            StringBuilder errorUserName = new StringBuilder();
            for (UserEntity entity : userEntityList) {
                errorUserName.append(entity.getName()).append(StringConstant.COMMA);
            }

            teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271008.getCode(), String.format(UserTeamErrorCodeEnum.API_ERROR_271008.getMsg(), errorUserName.substring(0, errorUserName.length() - 1)),
                    errorName, UserTeamOperateTagEnum.TEAM_USER_ALL_OPERATE.getName(),dataId);
        }
        return teamBatchPojo;
    }

    /**
     * Description: 判断要删除的人员是否存在负责/协同团队中
     * @param oldUserList
     * @param newDelUserList
     * @param corpid
     * @param errorName
     * @param userTeamOperateTagEnum
     * @param dataId
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2021/12/30 22:25
     * @since
     */
    private TeamBatchPojo checkInTeamForDel(Set<String> oldUserList, Set<String> newDelUserList, String corpid, String errorName, UserTeamOperateTagEnum userTeamOperateTagEnum, Long dataId) throws XbbException {
        TeamBatchPojo teamBatchPojo = null;
        if (CollectionUtils.isNotEmpty(newDelUserList)) {
            //记录不存在团队中的人
            List<String> userList = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(oldUserList)){
                for (String userId : newDelUserList) {
                    if(!oldUserList.contains(userId)){
                        userList.add(userId);
                    }
                }
            }else{
                userList.addAll(newDelUserList);
            }
            List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, userList, true);
            if (CollectionsUtil.isEmpty(userEntityList)) {
                return teamBatchPojo;
            }
            StringBuilder errorUserName = new StringBuilder();
            for (UserEntity entity : userEntityList) {
                errorUserName.append(entity.getName()).append(StringConstant.COMMA);
            }

            teamBatchPojo = new TeamBatchPojo();
            if(Objects.equals(userTeamOperateTagEnum,UserTeamOperateTagEnum.DEL_MAIN)){
                teamBatchPojo.setCode(UserTeamErrorCodeEnum.API_ERROR_271010.getCode());
                commonHelp.singleFailMsg(errorName, userTeamOperateTagEnum.getName(), teamBatchPojo);
                teamBatchPojo.setFailMsgReason(String.format(UserTeamErrorCodeEnum.API_ERROR_271010.getMsg(), errorUserName.substring(0, errorUserName.length() - 1)));
            }else if(Objects.equals(userTeamOperateTagEnum,UserTeamOperateTagEnum.DEL_COUSER)){
                teamBatchPojo.setCode(UserTeamErrorCodeEnum.API_ERROR_271012.getCode());
                commonHelp.singleFailMsg(errorName, userTeamOperateTagEnum.getName(), teamBatchPojo);
                teamBatchPojo.setFailMsgReason(String.format(UserTeamErrorCodeEnum.API_ERROR_271012.getMsg(), errorUserName.substring(0, errorUserName.length() - 1)));
            }
            teamBatchPojo.setDataId(dataId);
        }
        return teamBatchPojo;
    }

    /**
     * 共享模式下的移交逻辑
     *
     * @param originUserId 需要被替换的负责人（移交功能使用）
     * @param changeUserId 替换的负责人
     * @param teamAfterModeProcessPOJO 校验返回的实体
     * @param dataId 主键id
     * @param nameOrSeriNoMap 主数据id和名称/编号的一个map
     * @param oldMainUserList 老负责人列表
     * @param newDelMainUserList 新的负责人删除列表
     * @param oldCoUserList 老的协同人列表
     * @param newAddMainUserList 新增负责人列表
     * @param newDelCoUserList 新的协同人删除列表
     *
     */
    private void shareHandleOver(String originUserId, String changeUserId, TeamAfterModeProcessPOJO teamAfterModeProcessPOJO,
                                 Long dataId, Map<Long, String> nameOrSeriNoMap, Set<String> oldMainUserList, Set<String> newDelMainUserList,
                                 Set<String> oldCoUserList, Set<String> newAddMainUserList, Set<String> newDelCoUserList, String platForm) {
        //移交的一些校验逻辑,移动端不用做多负责人校验（历史遗留问题）
        if (CollectionsUtil.isNotEmpty(oldMainUserList) && oldMainUserList.size() > BasicConstant.ONE && !Objects.equals(platForm, PlatFormEnum.DINGTALK.getValue())) {
            String errorName = nameOrSeriNoMap.get(dataId);
            TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271016.getCode(), UserTeamErrorCodeEnum.API_ERROR_271016.getMsg(),
                    errorName, OperateTypeEnum.HANDOVER.getName(), dataId);
            teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
            return;
        }
        if (CollectionsUtil.isNotEmpty(oldMainUserList) && oldMainUserList.contains(changeUserId) && Objects.equals(changeUserId, originUserId)) {
            String errorName = nameOrSeriNoMap.get(dataId);
            TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271017.getCode(), UserTeamErrorCodeEnum.API_ERROR_271017.getMsg(),
                    errorName, OperateTypeEnum.HANDOVER.getName(), dataId);
            teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
            return;
        }
        if (CollectionsUtil.isNotEmpty(oldMainUserList) && oldMainUserList.contains(changeUserId)) {
            String errorName = nameOrSeriNoMap.get(dataId);
            TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271018.getCode(), UserTeamErrorCodeEnum.API_ERROR_271018.getMsg(),
                    errorName, OperateTypeEnum.HANDOVER.getName(), dataId);
            teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
            return;
        }
        //移交的相关实体封装，协同人变为负责人，删除负责人，新增负责人
        if (Objects.isNull(originUserId) && CollectionUtils.isNotEmpty(oldMainUserList))  {
            //只有移动端才会有需要被替换的用户id，否则其它的情况的话默认取团队老负责人的第一个
            originUserId = oldMainUserList.stream().findFirst().get();
        }
        if (Objects.nonNull(originUserId)) {
            newDelMainUserList = Collections.singletonList(originUserId).stream().collect(Collectors.toSet());
        }
        Set<String> coToMainUserList = new HashSet<>();
        if (oldCoUserList.contains(changeUserId)) {
            coToMainUserList = Collections.singletonList(changeUserId).stream().collect(Collectors.toSet());
        }else {
            newAddMainUserList = Collections.singletonList(changeUserId).stream().collect(Collectors.toSet());
        }
        teamAfterModeProcessPOJO.setDelMainUserList(newDelMainUserList);
        teamAfterModeProcessPOJO.setDelCoUserList(newDelCoUserList);
        teamAfterModeProcessPOJO.setAddMainUserList(newAddMainUserList);
        teamAfterModeProcessPOJO.setCoToMainUserList(coToMainUserList);
    }

    /**
     * 隔离模式下的移交逻辑
     *
     * @param originUserId
     * @param changeUserId
     * @param dataId
     * @param nameOrSeriNoMap
     * @param teamAfterModeProcessPOJO
     * @param newDelMainUserList
     * @param newAddMainUserList
     * @param oldMainUserList
     * @param oldCoUserList
     * @param loginUser                操作人（当前登录人）
     * @param saasMark
     * @param businessType
     * @param formId
     */
    private void isolationHandleOver(String corpid, String originUserId, String changeUserId, Long dataId, Map<Long, String> nameOrSeriNoMap,
                                     TeamAfterModeProcessPOJO teamAfterModeProcessPOJO, Set<String> newDelMainUserList, Set<String> newAddMainUserList,
                                     Set<String> oldMainUserList, Set<String> oldCoUserList, Map<String, Set<String>> oldTeamCoUserRelMap, UserVO loginUser, Integer saasMark, Integer businessType, Long formId) {
        List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid,Arrays.asList(originUserId,changeUserId), true);
        Map<String, String> userNameMap = userEntityList.stream().collect(Collectors.toMap(UserEntity::getUserId, v -> v.getName()));
        if(Objects.nonNull(originUserId) && !oldMainUserList.contains(originUserId)){
            //所选的负责人的团队不存在
            String errorName = nameOrSeriNoMap.get(dataId);
            TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271009.getCode(), String.format(UserTeamErrorCodeEnum.API_ERROR_271009.getMsg(),userNameMap.get(originUserId)),
                    errorName, UserTeamOperateTagEnum.HANDOVER.getName(), dataId);
            teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
            return;
        }
        if (oldMainUserList.contains(changeUserId) || oldCoUserList.contains(changeUserId)) {
            String errorName = nameOrSeriNoMap.get(dataId);
            TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271008.getCode(), String.format(UserTeamErrorCodeEnum.API_ERROR_271008.getMsg(), userNameMap.get(changeUserId)),
                    errorName, OperateTypeEnum.HANDOVER.getName(), dataId);
            teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
            return;
        }



        if (!isolationHandleOverPermissionCheck(corpid, originUserId, dataId, oldMainUserList, oldCoUserList, loginUser, saasMark, businessType, formId)) {
            String errorName = nameOrSeriNoMap.get(dataId);
            TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271040.getCode(), UserTeamErrorCodeEnum.API_ERROR_271040.getMsg(),
                    errorName, OperateTypeEnum.HANDOVER.getName(), dataId);
            teamAfterModeProcessPOJO.setTeamBatchPojo(teamBatchPojo);
            return;
        }


        newDelMainUserList = Collections.singletonList(originUserId).stream().collect(Collectors.toSet());
        newAddMainUserList = Collections.singletonList(changeUserId).stream().collect(Collectors.toSet());
        Map<String, Set<String>> changeTeamMainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        changeTeamMainUserMap.put(changeUserId , oldTeamCoUserRelMap.get(originUserId));
        teamAfterModeProcessPOJO.setDelMainUserList(newDelMainUserList);
        teamAfterModeProcessPOJO.setAddMainUserList(newAddMainUserList);
        teamAfterModeProcessPOJO.setChangeTeamMainUserMap(changeTeamMainUserMap);
    }

    /**
     * Description: 隔离模式下移交权限的判断
     * @param corpid
	 * @param originUserId
	 * @param dataId
	 * @param oldMainUserList
	 * @param oldCoUserList
	 * @param loginUser
	 * @param saasMark
	 * @param businessType
	 * @param formId
     * @return boolean
     * @throws
     * @author 魏荣杰
     * @date 2022/9/19 19:34
     * @since
     */
    private boolean isolationHandleOverPermissionCheck(String corpid, String originUserId, Long dataId, Set<String> oldMainUserList, Set<String> oldCoUserList, UserVO loginUser, Integer saasMark, Integer businessType, Long formId) {
        Long menuId = 0L;
        if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark)) {
            PaasFormEntity paasFormEntity = paasFormModel.getByFormId(formId, corpid);
            menuId = paasFormEntity.getMenuId();
        }

        // 移交的操作权限
        if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
            HandoverPermissionAliasEnum handoverPermissionAlias = HandoverPermissionAliasEnum.getByCode(businessType);
            if (!loginUser.getPermSet().contains(handoverPermissionAlias.getAlias())) {
                return false;
            }
        }

        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(loginUser, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.getByCode(saasMark), businessType, menuId);
        // 超管，全公司数据权限
        if (Objects.equals(dataPermission, DataPermissionEnum.ALL.getCode())) {
            return true;
        } else {
            // 原负责人本人
            if (Objects.nonNull(originUserId) && oldMainUserList.contains(originUserId) && Objects.equals(originUserId, loginUser.getUserId())) {
                return true;
            } else {

                // 操作人有原负责人的数据权限
                List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, loginUser.getUserId(), loginUser.getCorpid(), BasicConstant.ZERO,false);

                if (userIdIn.contains(originUserId)) {
                    //在团队作为不可编辑协同人，无法移交
                    if (oldCoUserList.contains(loginUser.getUserId())) {
                        Map<String, Object> param = new HashMap<>();
                        param.put(ParameterConstant.CORPID, corpid);
                        param.put(ParameterConstant.USER_ID, loginUser.getUserId());
                        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                        List<UserTeamEntity> userTeamEntities = businessUserTeamHelp.getUserTeamListByParams(Collections.singletonList(dataId), businessType, param);
                        if (CollectionsUtil.isNotEmpty(userTeamEntities)) {
                            UserTeamEntity userTeamEntity = userTeamEntities.get(0);
                            Integer formPermission = userTeamEntity.getFormPermission();
                            if (Objects.isNull(formPermission)) {
                                formPermission = FormCoUserDefaultPermissionEnum.getDefaultPerByBus(businessType);
                            }

                            if (Objects.equals(formPermission, CoUserPermissionEnum.EDIT.getPermissionValue())) {
                                return true;
                            }
                        }
                    } else {
                        return true;
                    }
                } else {
                    return false;
                }

            }
        }
        return false;
    }


    /**
     * @param
     * @param code
     * @param msg
     * @Description: 封装报错信息，用于联合创建，下游单据的团队报错封装
     * @return: java.lang.String
     * @Author: shen.yang
     * @Date: 2022/6/10  15:47
     */
    public String formatErrorMessage(Integer code, String msg, XbbRefTypeEnum xbbRefTypeEnum){
        String message;
//        ErrorCodeEnum codeEnum = ErrorCodeEnum.getByCode(code);
        switch (code){
//            case ErrorCodeEnum.API_ERROR_390005:
            case 390005:
                message = String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.NO_DEL_OWNER_PERMISSION),xbbRefTypeEnum.getName());
                break;
//            case ErrorCodeEnum.API_ERROR_390006:
            case 390006:
                message = String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.NO_DEL_CO_USER_PERMISSION),xbbRefTypeEnum.getName());
                break;
//            case ErrorCodeEnum.API_ERROR_390007:
            case 390007:
                message = String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.NO_ADD_OWNER_PERMISSION),xbbRefTypeEnum.getName());
                break;
//            case ErrorCodeEnum.API_ERROR_390008:
            case 390008:
                message = String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.NO_ADD_CO_USER_PERMISSION),xbbRefTypeEnum.getName());
                break;
//            case SystemErrorCodeEnum.API_ERROR_100127:
//            case BuinessDefaultErrorCodeEnum.API_ERROR_200024:
//            case SystemErrorCodeEnum.API_ERROR_100004:
//            case ErrorCodeEnum.API_ERROR_271021:
//            case ErrorCodeEnum.API_ERROR_271032:
//            case ErrorCodeEnum.API_ERROR_271015:
//            case BuinessDefaultErrorCodeEnum.API_ERROR_200016:
//            case ErrorCodeEnum.API_ERROR_271002:
//            case ErrorCodeEnum.API_ERROR_271009:
//            case ErrorCodeEnum.API_ERROR_271014:
//            case ErrorCodeEnum.API_ERROR_271012:
//            case ErrorCodeEnum.API_ERROR_271008:
            case 100127:
            case 200024:
            case 100004:
            case 271021:
            case 271032:
            case 271015:
            case 200016:
            case 271002:
            case 271009:
            case 271014:
            case 271012:
            case 271008:
                message = xbbRefTypeEnum.getName() + msg;
                break;
            default:
                message = msg;
        }

        return message;
    }

}
